# encoding: utf-8
import base64
import datetime
import os
import subprocess

from flask import Flask, Response

import flask
import json
import requests
import logging
import threading
import time
import models
# import readRTSP
import sys
import moniterFace
import moniterCP
import socketNet

app = Flask(__name__)


baseUrl = 'http://192.168.1.102:8081/face'
basePlateUrl = 'http://192.168.1.102:8081/'



# 获取设备最近识别记录
@app.route('/getLastImage', methods=['POST'])
def getLastImage():
    deviceNum = flask.request.form.get('deviceNum')
    num = flask.request.form.get('num')
    camType = flask.request.form.get('type')  # camType 0=face  1=plate
    res = {}
    result = None
    try:
        if int(camType) == 0:
            result = models.FaceRecordThread().selectLastImg(deviceNum, num)
        elif int(camType) == 1:
            result = models.PlateRecordThread().selectLastImg(deviceNum, num)
    except Exception, e:
        print(e)
        print '__________________'
        res['code'] = -1
        res['imageList'] = []
    else:
        res['code'] = 0
        res['imageList'] = result

    print res
    return json.dumps(res, ensure_ascii=False)


# 获取车牌检测记录
@app.route('/plateRecord', methods=['POST'])
def plateRecord():
    deviceNum = flask.request.form.get('deviceNum')
    plateNum = flask.request.form.get('plateNum')
    startTime = flask.request.form.get('startTime')
    endTime = flask.request.form.get('endTime')

    res = {}
    result = None
    try:
        result = models.PlateRecordThread().selectLastImg(deviceNum, None)
    except Exception:
        res['code'] = -1
        res['list'] = []
    else:
        res['code'] = 0
        res['list'] = result
    return json.dumps(res, ensure_ascii=False)


# 获取人脸检测记录
@app.route('/faceRecord', methods=['POST'])
def faceRecord():
    deviceNum = flask.request.form.get('deviceNum')
    num = flask.request.form.get('num')

    res = {}
    result = None
    try:
        result = models.FaceRecordThread().select(deviceNum, num)
    except Exception:
        res['code'] = -1
        res['list'] = []
    else:
        res['code'] = 0
        res['list'] = result
    return json.dumps(res, ensure_ascii=False)


# 获取车牌预警记录
@app.route('/plateWarning', methods=['POST'])
def plateWarning():
    # deviceNum = flask.request.form.get('deviceNum')
    # plateNum = flask.request.form.get('plateNum')
    startTime = flask.request.form.get('startTime')
    endTime = flask.request.form.get('endTime')
    print startTime
    print endTime
    res = {}
    result = None
    # try:
    result = models.PlateWarningThread().select(startTime, endTime)
    # except Exception:
    #     res['code'] = -1
    #     res['carList'] = []
    # else:
    res['code'] = 0
    res['carList'] = result
    return json.dumps(res, ensure_ascii=False)


# 获取人脸预警记录
@app.route('/faceWarning', methods=['POST'])
def faceWarning():
    startTime = flask.request.form.get('startTime')
    endTime = flask.request.form.get('endTime')

    print startTime
    print endTime
    res = {}
    result = None
    # try:
    result = models.FaceWarningThread().select(startTime, endTime)
    # except Exception:
    #     res['code'] = -1
    #     res['faceList'] = []
    # else:
    res['code'] = 0
    res['faceList'] = result

    return json.dumps(res, ensure_ascii=False)



# 获取设备列表
@app.route('/getDeviceList', methods=['POST'])
def getDeviceList():
    res = {}
    result = None
    try:
        result = models.DeviceThread().selectAll()
    except Exception:
        res['code'] = -1
        res['deviceList'] = []
    else:
        res['code'] = 0
        res['deviceList'] = result
    res['baseUrl'] = baseUrl
    res['basePlateUrl'] = basePlateUrl
    return json.dumps(res, ensure_ascii=False)


# 人脸识别服务开启关闭
@app.route('/faceServiceSwitch', methods=['POST'])
def faceServiceSwitch():
    deviceNum = flask.request.form.get('deviceNum').encode('utf-8')
    flag = flask.request.form.get('flag').encode('utf-8')  # 1 start  0 close

    if int(flag) == 1:
        device = models.DeviceThread().selectOne(deviceNum)
        moniterFace.startFace(device)
    else:
        moniterFace.stopFace(deviceNum)

    models.DeviceThread().updatePlateState(deviceNum,flag)
    res = {}
    res['code'] = 0
    return json.dumps(res, ensure_ascii=False)


# 车牌识别服务开启关闭
@app.route('/plateServiceSwitch', methods=['POST'])
def plateServiceSwitch():
    flag = flask.request.form.get('flag')  # 0=face 1==plate
    deviceNum = flask.request.form.get('deviceNum')

    res = {}
    try:
        if int(flag) == 1:
            ip = flask.request.form.get('ip')
            userName = flask.request.form.get('userName')
            passwd = flask.request.form.get('passwd')
            startcheck(ip, userName,passwd, deviceNum)
        elif int(flag) == 0:
            stopcheck(deviceNum)
    except Exception,e:
        print str(e)
        res['code'] = -1
    else:
        res['code'] = 0
    models.DeviceThread().updatePlateState(deviceNum,flag)
    return json.dumps(res, ensure_ascii=False)


# 车牌识别服务开启状态回调
@app.route('/plateState', methods=['POST'])
def plateState():
    state = flask.request.form.get('state')  # 0=face 1==plate
    deviceNum = flask.request.form.get('deviceNum')

    res = {}
    try:
        models.DeviceThread().updatePlateState(deviceNum, state)
        if state == '0':
            # 状态入库, 通知页面
            param = {}
            param['state'] = state
            param['deviceNum'] = deviceNum
            socketNet.sendPro("W14", param)
    except Exception:
        res['code'] = -1
    else:
        res['code'] = 0
    return json.dumps(res, ensure_ascii=False)


# 车牌识别图片回调请求
# 功能: 入库, 推送页面实时图片, 判断预警
@app.route('/plateImage', methods=['POST'])
def plateImage():
    data = json.loads(flask.request.get_data())
    # smallImage = flask.request.form.get('smallImage')
    # bigImage = flask.request.form.get('bigImage')
    # deviceNum = flask.request.form.get('deviceNum')
    # plateNum = flask.request.form.get('plateNum')
    print data
    smallImage =data['smallImage'].encode('utf-8')
    bigImage = data['bigImage'].encode('utf-8')
    deviceNum = data['deviceNum'].encode('utf-8')
    plateNum = data['plateNum'].encode('utf-8')

    logging.error(str(plateNum))

    res = {}
    # try:
        # TODO: 获取最新GPS坐标, 入库
    gpsData = moniterCP.getGPSData()
    models.PlateRecordThread().insertPlateInfo(
        smallImage, bigImage, plateNum, deviceNum,gpsData)
    # 分发数据到页面
    sendData = {}
    # sendData['smallImage'] = smallImage
    # sendData['bigImage'] = bigImage
    # sendData['plateNum'] = plateNum
    # sendData['deviceNum'] = deviceNum

    sendData['vrImageurl'] = smallImage
    sendData['vrBigImageurl'] = bigImage
    # sendData['plateNum'] = plateNum
    sendData['deviceNumber'] = deviceNum
    print sendData
    socketNet.sendPro("W12", sendData)

    # 判断是否有预警信息, 是->入预警库 分发预警数据到页面
    plateBlackCount = models.PlateBlackThread().selectPlateByNum(plateNum)
    if plateBlackCount > 0 :
        print 'senW03'
        # sendData['pbLogo'] = plateBlack.PB_LOGO
        # sendData['pbColor'] = plateBlack.PB_COLOR
        # sendData['pbOwnerName'] = plateBlack.PB_OWNER_NAME
        # sendData['pbOwnerPhone'] = plateBlack.PB_OWNER_PHONE
        # sendData['pbNote'] = plateBlack.PB_NOTE
        sendBlackData = {}
        sendBlackData['vyjBigImageurl'] = bigImage
        sendBlackData['vyjImageurl'] = smallImage
        socketNet.sendPro("W03", sendBlackData)

        prId = models.PlateRecordThread().selectPlateById(smallImage)
        plateBlack =  models.PlateBlackThread().selectById(plateNum)
        print str(prId)
        print str(plateBlack.PB_ID)
        models.PlateWarningThread().insert(prId,plateBlack.PB_ID)

    # except Exception,e:
    #     print str(e)
    #     res['code'] = -1
    # else:
    #     res['code'] = 0
    return json.dumps(res, ensure_ascii=False)

@app.route('/wifiprobe', methods=['POST'])
def wifiprobe():
    data = flask.request.form.get('data').encode('utf8')
    moniterCP.wifiprobe(data)
    return 'post'


def startcheck(ip, userName, passwd, deviceNum):

    msgline = './plate ' + ip + ' ' + userName + ' ' + passwd + ' ' + deviceNum
    logging.error(msgline)
    start_thread = threading.Thread(
        target=moniterCP.startCpExec, name="startCpThread", args=(msgline, deviceNum,))
    # start_thread.setDaemon(True)
    start_thread.start()
    resp = {}
    resp['code'] = '1'

    return json.dumps(resp)


def stopcheck(deviceNum):
    resp = moniterCP.stopCP(deviceNum)
    return json.dumps(resp)


# 拉取设备列表接口
@app.route('/pullDeviceList', methods=['POST'])
def pullDeviceList():
    macId = flask.request.form.get('macId')
    return pullDeviceListHttp(macId)


# 拉取设备列表方法
def pullDeviceListHttp(macId):
    url = "http://cg.visualdeep.com:18200/CityInspectors/getDevice.json"
    postDict = {}
    postDict["pcNumber"] = moniterFace.macId
    response = requests.post(url, json=postDict)
    jsonResp = json.loads(response.text.encode('utf8'))

    oldStateAll = models.DeviceThread().selectAll()

    if jsonResp != None:
        for oldDev in oldStateAll:
            for dev in jsonResp:
                if dev['deviceNumber'] == oldDev['deviceNumber']:
                    dev['deviceState'] = oldDev['deviceState']
                    
        models.DeviceThread().insertDevice(jsonResp)
    return '{"code":0}'


# 拉取人脸黑名单接口
@app.route('/pullFaceBlack', methods=['POST'])
def pullFaceBlack():
    # macId = flask.request.form.get('macId')
    return socketNet.pullFaceBlackHttp(moniterFace.macId)




# 拉取车牌黑名单接口
@app.route('/pullPlateBlack', methods=['POST'])
def pullPlateBlack():
    macId = flask.request.form.get('macId')
    return socketNet.pullPlateBlackHttp(macId)




def getDevice():
    result = models.DeviceThread().selectAll()
    for data in result:
        if int(data['deviceState']) == 1:
            if int(data['deviceState']) == 0:
                moniterFace.startFace(data)
            else:
                moniterFace.startcheck(ip, userName,passwd, deviceNum)

if __name__ == '__main__':
    macId = "HS001"
    pullDeviceListHttp(macId)
    socketNet.pullFaceBlackHttp(macId)
    socketNet.pullPlateBlackHttp(macId)
    #getDevice()
    

    logging.basicConfig(level=logging.INFO,
                        format='%(asctime)s %(filename)s(%(funcName)s)[line:%(lineno)d] %(levelname)s %(message)s',
                        datefmt='%a, %d %b %Y %H:%M:%S')

    threadFaceStartFace = threading.Thread(target=socketNet.threadStartFace, name="threadStartFace",args = ('',))
    threadFaceStartFace.start()
    threadStartFace = threading.Thread(target=socketNet.threadStartSocket, name="threadStartSocket",args = ('',))
    threadStartFace.start()
    probeThread = threading.Thread(target=moniterCP.probeThreadStart, name="probeThreadStart", args=('',))
    probeThread.setDaemon(True)
    probeThread.start()
    gpsThread = threading.Thread(target=moniterCP.gpsThreadStart, name="gpsThreadStart", args=('',))
    gpsThread.start()
    # uploadThread = threading.Thread(target=socketNet.uploadFacePlateData, name="uploadFacePlateData", args=('',))
    # uploadThread.start()
    app.run(host='0.0.0.0', debug=False, port=9999, )
